package com.xianye.erp.service.product.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.annotation.Resource;

import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AliexpressPostproductRedefiningFindaeproductbyidRequest;
import com.taobao.api.request.AliexpressPostproductRedefiningFindproductinfolistqueryRequest;
import com.taobao.api.response.AliexpressPostproductRedefiningFindaeproductbyidResponse;
import com.taobao.api.response.AliexpressPostproductRedefiningFindproductinfolistqueryResponse;
import com.xianye.erp.dao.base.DaoSupport;
import com.xianye.erp.factory.ApiFacade;
import com.xianye.erp.service.product.ProductManager;
import com.xianye.erp.util.HttpRequestor;
import com.xianye.erp.util.PageData;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;


@Service("refreshProductService")
public class RefreshProductService {
	protected Logger log = Logger.getLogger(this.getClass());
	@Autowired
	private JdbcTemplate jdbc;
	@Resource(name = "productService")
	private ProductManager productService;
	@Resource(name = "daoSupport")
	private DaoSupport dao;
	@Autowired
	private ProductAPI productAPI;
	@Autowired
	private ApiFacade facade;


	private final static Executor executor = Executors.newCachedThreadPool();//启用多线程
	private List<JSONObject> products = new ArrayList<>();
	private static final String ONSELLING = "onSelling";
	private static final String OFFLINE = "offline";
	private static final String AUDITING  = "auditing";
	private static final String EDITINGREQUIRED = "editingRequired";
	
	public RefreshProductService(){
		
	}

	public void refresh(){
		try {
			List<PageData> list = getStore();
//			PageData store = list.get(2);
//			refreshOneStore(store);
//			productAPI.saveProduct(products);
//			products.clear();
			for(int i=0;i<list.size();i++){
				PageData store = list.get(i);
				refreshOneStore(store);
				//数据已存入redis,开始处理数据
				productAPI.saveProduct(products);
				products.clear();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void refreshStoreById(PageData pd ){
		try {
				PageData store = getStoreById(pd);
				refreshOneStore(store);
				//数据已存入redis,开始处理数据
				productAPI.saveProduct(products);
				products.clear();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public List<PageData> getStore() throws Exception{
		return (List<PageData>) dao.findForList("StoreMapper.list", new PageData());
	}
	public PageData getStoreById(PageData pd) throws Exception{
		return  (PageData) dao.findForObject("StoreMapper.findByStoreId", pd);
	}
	public void refreshOneStore(PageData store){
		try {
			log.info("开始调用店铺"+store.get("ID")+"的"+ONSELLING +"商品");
			getTypeList(store,ONSELLING);
			log.info("开始调用店铺"+store.get("ID")+"的"+OFFLINE +"商品");
		    getTypeList(store,OFFLINE);
		    log.info("开始调用店铺"+store.get("ID")+"的"+AUDITING +"商品");
			getTypeList(store,AUDITING);
			log.info("开始调用店铺"+store.get("ID")+"的"+EDITINGREQUIRED +"商品");
			getTypeList(store,EDITINGREQUIRED);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("开始调用店铺"+store.get("ID")+"商品出现异常");
		}
	}
	/**
	 * 获取一个店铺中不同类型的商品信息
	 * @param type
	 * @throws Exception
	 */
	public  void  getTypeList(PageData store,String type) throws Exception{
		try {
			JSONObject json  = getProductList(store,type,1L);
			//dealData(store,json);
			//System.out.println("分界线1--------------------"+json.getLong("total_page"));
			if(json!=null){
				dealData(store,json);
				int page =json.getInt("total_page");
				for(int i=2;i<=page;i++){
					JSONObject res = getProductList(store,type,(long)i);
					dealData(store,res);
					System.out.println("分界线--------------------"+(long)i);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 *
	 */
	public void dealData(final PageData store,final JSONObject result){
		try {
			JSONArray productList = new JSONArray();
			if(result!=null && result.containsKey("aeop_a_e_product_display_d_t_o_list")){
				JSONObject list = result.getJSONObject("aeop_a_e_product_display_d_t_o_list");
				if(list.containsKey("aeop_ae_product_display_sample_dto")){
					productList = list.getJSONArray("aeop_ae_product_display_sample_dto");
				}
			}
			if(productList!=null && productList.size()>0){
				final CountDownLatch latch = new CountDownLatch(productList.size());
				//同时启动20线程读取远程接口数据
				for(int i=0;i<productList.size();i++){
					final JSONObject product = productList.getJSONObject(i);
					final int j=i;
					new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								if(product!=null && product.get("product_id")!=null){
									JSONObject detail = getOrderDetail(store, product.getLong("product_id"));
									detail.accumulate("STORE_ID", store.get("ID"));
									product.accumulate("detail", detail);
									System.out.println(j+"------------>");
									//System.out.println("detail:"+detail.toString());
									//System.out.println(product.toString());

									products.add(product);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}finally{
								latch.countDown();
							}
						}
					}).start();
				}
				latch.await();
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("查找到产品详情,放入redis是出错");
		}
		
	}
	
	public JSONObject  getProductList(PageData store, String type, Long currentPage){
		try {
			TaobaoClient client = new DefaultTaobaoClient(facade.getUrl(), facade.getAppkey(), facade.getSecret());
			AliexpressPostproductRedefiningFindproductinfolistqueryRequest req = new AliexpressPostproductRedefiningFindproductinfolistqueryRequest();
			AliexpressPostproductRedefiningFindproductinfolistqueryRequest.AeopAeProductListQuery obj1 = new AliexpressPostproductRedefiningFindproductinfolistqueryRequest.AeopAeProductListQuery();
			obj1.setCurrentPage(currentPage);
			obj1.setPageSize(50L);
			obj1.setProductStatusType(type);
			req.setAeopAEProductListQuery(obj1);
			AliexpressPostproductRedefiningFindproductinfolistqueryResponse rsp = client.execute(req, store.getString("access_token"));
			JSONObject res = JSONObject.fromObject(rsp.getBody());
			if(res.containsKey("aliexpress_postproduct_redefining_findproductinfolistquery_response")){
				JSONObject response = res.getJSONObject("aliexpress_postproduct_redefining_findproductinfolistquery_response");
				if(response.containsKey("result")){
					return response.getJSONObject("result");
				}
			}
			return null;
		} catch (Exception e) {
			log.error("获取产品列表发生异常",e);
			e.printStackTrace();
			return null;
		}
		
	}
	public JSONObject getOrderDetail(PageData store, Long productId){
		try {
			TaobaoClient client = new DefaultTaobaoClient(facade.getUrl(), facade.getAppkey(), facade.getSecret());
			AliexpressPostproductRedefiningFindaeproductbyidRequest req = new AliexpressPostproductRedefiningFindaeproductbyidRequest();
			req.setProductId(productId);
			AliexpressPostproductRedefiningFindaeproductbyidResponse rsp = client.execute(req, store.getString("access_token"));
			JSONObject res = JSONObject.fromObject(rsp.getBody());
			if(res.containsKey("aliexpress_postproduct_redefining_findaeproductbyid_response")){
				JSONObject resp = res.getJSONObject("aliexpress_postproduct_redefining_findaeproductbyid_response");
				if(resp.containsKey("result")){
					return  resp.getJSONObject("result");
				}
			}
			return null;
		} catch (Exception e) {
			log.error("获取产品详情发生异常",e);
			e.printStackTrace();
			return null;
		}
	}
	
}
